#include "curveitem.h"
#include <QPixmap>
#include <QColorDialog>

CurveItem::CurveItem(QString tag, QColor curveColor)
	:QTreeWidgetItem()
{
	m_x_cnt = 0;
	m_tag = tag;
	m_color = curveColor;
	
	setCheckState(0, Qt::Checked);
	QPixmap pixmap = QPixmap(CURVE_LENGEND_W, CURVE_LENGEND_H);
	pixmap.fill(m_color);
	setData(CURVE_LENGEND_INDEX, Qt::DecorationRole, pixmap);
	
	m_curve.setPen(m_color);
	m_curve.setRenderHint(QwtPlotItem::RenderAntialiased, true);
	setText(CURVE_TEXT_INDEX, m_tag);
	setFlags(flags() & (~Qt::ItemIsSelectable));
}

CurveItem::~CurveItem()
{

}

void CurveItem::setCurveColor(QColor curveColor)
{
	m_color = curveColor;
	QPixmap pixmap = QPixmap(CURVE_LENGEND_W, CURVE_LENGEND_H);
	pixmap.fill(m_color);
	setData(CURVE_LENGEND_INDEX, Qt::DecorationRole, pixmap);
	emit ColorChanged(m_color);
}

QColor CurveItem::getCurveColor(void)
{
	return m_color;
}

QString CurveItem::getTag(void)
{
	return m_tag;
}

void CurveItem::addPoint(float y)
{
	m_points << QPointF(m_x_cnt++, y);
	m_curve.setSamples(m_points);
}

void CurveItem::attachPlot(QwtPlot *plot)
{
	m_curve.attach(plot);
}

void CurveItem::detachPlot(void)
{
	m_curve.detach();
}

void CurveItem::delPoint(void)
{
	m_points.clear();
	m_x_cnt = 0;
	m_curve.setSamples(m_points);
}

void CurveItem::reFresh(void)
{
	setCheckState(0, Qt::Checked);
	QPixmap pixmap = QPixmap(CURVE_LENGEND_W, CURVE_LENGEND_H);
	pixmap.fill(m_color);
	setData(CURVE_LENGEND_INDEX, Qt::DecorationRole, pixmap);

	m_curve.setPen(m_color);
	m_curve.setRenderHint(QwtPlotItem::RenderAntialiased, true);
	setText(CURVE_TEXT_INDEX, m_tag);
	setFlags(flags() & (~Qt::ItemIsSelectable));

	m_curve.setSamples(m_points);
}

void CurveItem::onItemClicked(int column)
{
	qDebug() << column;
	if (CURVE_LENGEND_INDEX == column)
	{
		QColor c = QColorDialog::getColor(m_color);
		if (c.isValid())
		{
			m_color = c;
			reFresh();
		}
	}
}

CurveItem& CurveItem::operator =(const CurveItem &other)
{
	this->m_tag = other.m_tag;
	this->m_color = other.m_color;
	this->m_points = other.m_points;
	this->m_x_cnt = other.m_x_cnt;
	return *this;
}

#ifndef QT_NO_DATASTREAM  
QDataStream& operator>>(QDataStream &in, CurveItem &data)
{
	in >> data.m_tag >> data.m_color >> data.m_points >> data.m_x_cnt;
	data.reFresh();
	return in;
}

QDataStream& operator<<(QDataStream &out, CurveItem &data)
{
	out << data.m_tag << data.m_color << data.m_points << data.m_x_cnt;
	return out;
}
#endif